reading-notes

The Call Stack and Debugging

Call stack

- A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.
function greeting() {
   // [1] Some codes here
   sayHi();
   // [2] Some codes here
}
function sayHi() {
   return "Hi!";
}

// Invoke the `greeting` function
greeting();

// [3] Some codes here

This is what happens when the code is run:

  1. When secondFunction() gets executed, an empty stack frame is created. It is the main (anonymous) entry point of the program.
  2. secondFunction() then calls firstFunction()which is pushed into the stack.
  3. firstFunction() returns and prints “Hello from firstFunction” to the console.
  4. firstFunction() is pop off the stack.
  5. The execution order then move to secondFunction().
  6. secondFunction() returns and print “The end from secondFunction” to the console.
  7. secondFunction() is pop off the stack, clearing the memory.

The key takeaways from the call stack are:

  1. It is single-threaded. Meaning it can only do one thing at a time.
  2. Code execution is synchronous.
  3. A function invocation creates a stack frame that occupies a temporary memory.
  4. It works as a LIFO — Last In, First Out data structure.

Debugging

  1. Types of error messages
    • Reference errors
    • Syntax errors
    • Range errors
    • Type errors
  2. Debugging